package top.lyc829.zzl_android.ui.profile.follow.user_detail;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityOtherUserDetailBinding;
import top.lyc829.zzl_android.logic.bean.LiveEventMsg;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.UserInfoBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.FellowType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.ui.profile.ConcernedViewModel;
import top.lyc829.zzl_android.ui.profile.UserFansNumberViewModel;
import top.lyc829.zzl_android.ui.profile.follow.FollowActivity;
import top.lyc829.zzl_android.ui.profile.user_dtc.collect.UserCollectFragment;
import top.lyc829.zzl_android.ui.profile.user_dtc.dynamic.UserDynamicFragment;
import top.lyc829.zzl_android.ui.profile.user_dtc.travels.UserTravelsFragment;
import top.lyc829.zzl_android.ui.profile.user_fans.FansActivity;
import top.lyc829.zzl_android.ui.profile.user_fans.UserFansFragment;
import top.lyc829.zzl_android.ui.thing.dynamic_detail.DynamicDetailViewModel;

public class OtherUserDetailActivity extends AppCompatActivity {
    ActivityOtherUserDetailBinding binding;
    private OtherUserDetailViewModel mViewModel;
    private ConcernedViewModel cViewModel;
    private UserFansNumberViewModel uViewModel;

    MiniLoadingDialog mMiniLoadingDialog;

    int userid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityOtherUserDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mViewModel = new ViewModelProvider(this).get(OtherUserDetailViewModel.class);
        cViewModel=new ViewModelProvider(this).get(ConcernedViewModel.class);
        uViewModel=new ViewModelProvider(this).get(UserFansNumberViewModel.class);

        userid = getIntent().getIntExtra("id", -1);

        mMiniLoadingDialog =  WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.updateMessage("加载中");
        mMiniLoadingDialog.setCancelable(false);

        ViewPager2 viewPage2 = binding.viewPage2;
        viewPage2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                if (position == 0) {
                    UserDynamicFragment fragment1 = new UserDynamicFragment();
                    fragment1.setOtherUserId(userid);
                    return fragment1;
                } else if (position == 1) {
                    UserTravelsFragment fragment2=new UserTravelsFragment();
                    fragment2.setotherUserId(userid);
                    return fragment2;
                } else {
                    UserCollectFragment fragment3=new UserCollectFragment();
                    fragment3.setOtherUserid(userid);
                    return fragment3;
                }
            }

            @Override
            public int getItemCount() {
                return 3;
            }
        });
        TabLayoutMediator mediator = new TabLayoutMediator(binding.tabLayout2, viewPage2, ((tab, position) -> {
            if (position == 0) {
                tab.setText("动态");
            } else if (position == 1) {
                tab.setText("游记");
            } else if (position == 2) {
                tab.setText("收藏");
            }
        }));

        mediator.attach();
        observer();
        clickListener();

        mViewModel.getUserInfo(userid);
        cViewModel.getConcernedInfo(userid);

    }
    private void observer(){
        mViewModel.getUserInfoBeanMutableLiveData().observe(this, userInfoBean -> {
            binding.genderTextView.setVisibility(View.VISIBLE);
            binding.usernameTextView.setVisibility(View.VISIBLE);
            binding.signatureTextView.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(userInfoBean.getAvatarUrl())
                    .into(binding.headerImage);
            binding.usernameTextView.setText(userInfoBean.getNickname());
            binding.genderTextView.setText(userInfoBean.getGender());
            binding.signatureTextView.setText(userInfoBean.getSignature());
            //String.VlueOf()
        });

        cViewModel.getConcernedBeanMutableLiveData().observe(this,concernedInfoBean -> {
            binding.followUserNumber.setText(String.valueOf(concernedInfoBean.getRelation_user_num()));
            binding.followTeamNumber.setText(String.valueOf(concernedInfoBean.getRelation_team_num()));
            binding.followBaseNumber.setText(String.valueOf(concernedInfoBean.getRelation_base_num()));
        });

        uViewModel.getFansNumberBeanMutableLivedata().observe(this, integer->{
            binding.fansNumber.setText(String.valueOf(integer));
        });

        mViewModel.getFellowRelationShip(Utils.getUserId(), FellowType.USER, userid);


        mViewModel.getIsFellowLiveData().observe(this, integer -> {
            if (integer.equals(1)) {
                binding.userAttentioned.setText("已关注");
                binding.userAttentioned.setBackgroundResource(R.drawable.btn_attentioned);
            }else {
                binding.userAttentioned.setText("关注");
                binding.userAttentioned.setBackgroundResource(R.drawable.btn_un_attentioned);
            }
        });
        if(userid==Utils.getUserId())
        {
            binding.userAttentioned.setVisibility(View.INVISIBLE);
        } else {
            binding.userAttentioned.setVisibility(View.VISIBLE);
        }
    }

    private void clickListener(){
        binding.otheruserTitleBar.setLeftClickListener(v -> finish());

        binding.goFollowBase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OtherUserDetailActivity.this, FollowActivity.class);
                intent.putExtra("id",1);//跳转至指定页面
                intent.putExtra("na",userid);
                startActivity(intent);
            }
        });
        binding.goUserFans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OtherUserDetailActivity.this, FansActivity.class);
                intent.putExtra("id",userid);//跳转至指定页面
                startActivity(intent);
            }
        });
        binding.goFollowTeam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OtherUserDetailActivity.this, FollowActivity.class);
                intent.putExtra("id",2);
                intent.putExtra("na",userid);
                startActivity(intent);
            }
        });
        binding.goFollowUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OtherUserDetailActivity.this, FollowActivity.class);
                intent.putExtra("id",0);
                intent.putExtra("na",userid);
                startActivity(intent);
            }
        });

        binding.userAttentioned.setOnClickListener(v -> {
            if (!Utils.isLogin()) { // 保证用户登陆之后才能继续操作
                Utils.showToast("请先登录");
                Utils.goLogin(this);
            } else if (mViewModel.getIsFellowLiveData().getValue() != null) {

                binding.userAttentioned.setClickable(false);
                mMiniLoadingDialog.show();

                if(mViewModel.getIsFellowLiveData().getValue().equals(0)) {
                    Network.attention(Utils.getUserId(), FellowType.USER, userid, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {
                                // 重新获取点赞关系

                                runOnUiThread(() -> {
                                    binding.userAttentioned.setClickable(true);
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getIsFellowLiveData().setValue(1);
                                    Integer number = uViewModel.getFansNumberBeanMutableLivedata().getValue();
                                    if (number != null) {
                                        uViewModel.getFansNumberBeanMutableLivedata().setValue(number + 1);
                                    }
                                });


                            } else {
                                failed(new IOException());
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                binding.userAttentioned.setClickable(true);
                                mMiniLoadingDialog.dismiss();
                                Utils.showToast("关注失败");
                            });


                        }
                    });

                } else if (mViewModel.getIsFellowLiveData().getValue().equals(1)) {
                    Network.unAttention(Utils.getUserId(), FellowType.USER, userid, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {
                                // 重新获取点赞关系
                                runOnUiThread(() -> {
                                    binding.userAttentioned.setClickable(true);
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getIsFellowLiveData().setValue(0);
                                    Integer number = uViewModel.getFansNumberBeanMutableLivedata().getValue();
                                    if (number != null) {
                                        uViewModel.getFansNumberBeanMutableLivedata().setValue(number - 1);
                                    }

                                });
                            } else {
                                failed(new IOException());
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                binding.userAttentioned.setClickable(true);
                                mMiniLoadingDialog.dismiss();
                                Utils.showToast("取消关注失败");
                            });

                        }
                    });

                }
            }


        });



    }

    @Override
    protected void onResume() {
        super.onResume();
        uViewModel.getFansNumberInfo(userid);
    }

    @Override
    protected void onDestroy() {
        mMiniLoadingDialog.recycle();
        super.onDestroy();
    }
}